<template>
  <div class="app-container">
    <!--搜索-->
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      label-width="100px"
    >
      <el-form-item label="应用名称" prop="app">
        <el-select
          style="width: 200px"
          v-model="queryParams.app"
          placeholder="请选择"
          clearable
          size="small"
        >
          <el-option
            v-for="dict in userTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="城市" prop="city">
        <el-select
          style="width: 200px"
          v-model="queryParams.city"
          placeholder="请选择"
          clearable
          size="small"
        >
          <el-option
            v-for="dict in citysOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="推荐位名称" prop="name">
        <el-select
          style="width: 200px"
          v-model="queryParams.name"
          placeholder="请选择"
          clearable
          size="small"
        >
          <el-option
            v-for="dict in activitiesTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >查询</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['reviewActivities:management:export']"
          >新增</el-button
        >
      </el-form-item>
    </el-form>

    <!--列表-->
    <el-table
      v-loading="loading"
      @sort-change="changeTableSort"
      border
      :data="getActivitiesDetails"
    >
      <el-table-column
        label="应用名称"
        prop="appLabel"
        align="center"
        width="120"
      ></el-table-column>
      <el-table-column
        label="城市"
        prop="cityLabel"
        align="center"
        width="100"
      ></el-table-column>
      <el-table-column
        label="推荐位名称"
        prop="nameLabel"
        align="center"
        width="120"
      ></el-table-column>
      <el-table-column
        label="推荐位描述"
        prop="description"
        align="center"
        width="150"
      ></el-table-column>
      <el-table-column label="图片" align="center" width="120">
        <template slot-scope="scope">
          <img
            @click="handlePictureCardPreview({ url: scope.row.imageUrl })"
            width="100"
            :src="scope.row.imageUrl"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="顺序"
        prop="order"
        align="center"
        width="60"
      ></el-table-column>
      <el-table-column label="有效期" align="center">
        <template slot-scope="scope">
          <span>{{
            scope.row.effectiveStartTime
              ? parserDate(scope.row.effectiveStartTime)
              : "--"
          }}</span>
          至
          <span>{{
            scope.row.effectiveEndTime
              ? parserDate(scope.row.effectiveEndTime)
              : "--"
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        width="180"
        prop="createTime"
        sortable
        align="center"
      >
        <template slot-scope="scope">
          <span>{{
            scope.row.createTime ? parserDate(scope.row.createTime) : "--"
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        width="120"
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['reviewActivities:management:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['reviewActivities:management:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!--添加或者修改对话框-->
    <el-dialog
      :close-on-click-modal="false"
      :title="title"
      :visible.sync="openFather"
      width="800px"
      append-to-body
    >
      <el-form
        ref="formFather"
        :model="formFather"
        :rules="rules"
        label-width="100px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="城市" prop="city">
              <el-select
                style="width: 240px"
                v-model="formFather.city"
                placeholder="请选择"
                clearable
                size="small"
              >
                <el-option
                  v-for="dict in citysOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="顺序" prop="order">
              <el-input-number
                step-strictly
                v-model.number.trim="formFather.order"
                :step="1"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="应用名称" prop="app">
              <el-select
                style="width: 240px"
                v-model="formFather.app"
                placeholder="请选择"
                clearable
                size="small"
              >
                <el-option
                  v-for="dict in userTypeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="开始时间" prop="effectiveStartTime">
              <el-date-picker
                v-model="formFather.effectiveStartTime"
                type="datetime"
                placeholder="选择时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="推荐位名称" prop="name">
              <el-select
                style="width: 240px"
                v-model="formFather.name"
                placeholder="请选择"
                clearable
                size="small"
              >
                <el-option
                  v-for="dict in activitiesTypeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="结束时间" prop="effectiveEndTime">
              <el-date-picker
                v-model="formFather.effectiveEndTime"
                type="datetime"
                placeholder="选择时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="适用范围" prop="comCodeList">
              <el-checkbox-group
                v-model="formFather.comCodeList"
                :min="1"
                :max="2"
              >
                <el-checkbox
                  v-for="item in checkboxArr"
                  :label="item"
                  :key="item"
                  >{{ item }}</el-checkbox
                >
              </el-checkbox-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="推荐位描述" prop="description">
              <el-input
                maxlength="20"
                v-model="formFather.description"
                placeholder="请输入推荐位描述"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="上传图片" prop="imageUrl" ref="uploadpic">
              <el-upload
                class="upload"
                v-model="formFather.imageUrl"
                action="https://api.shulanfd.com/aist-filesvr-web/api/files"
                list-type="picture-card"
                :limit="1"
                :file-list="fileList"
                :data="{
                  filetype: '非活动图',
                  app: 'shulan',
                  module: '1',
                  sourceKey: '1'
                }"
                :on-exceed="onExceed"
                :on-preview="handlePictureCardPreview"
                :before-upload="beforeAvatarUpload"
                :on-remove="handleRemove"
                :on-success="handleSuccess"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="跳转类型">
              <el-select
                v-model="formFather.jumpType"
                placeholder="请选择"
                clearable
                size="small"
              >
                <el-option
                  v-for="dict in jumpList"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="跳转链接" prop="link">
              <el-input v-model="formFather.link" placeholder="请输入链接" maxlength="256"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="跳转参数" prop="param">
              <v-jsoneditor
                @json-change="onJsonChange"
                v-model="formFather.param"
                :options="codeOptions"
                :plus="true"
                @error="onError"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormFather">确 定</el-button>
        <el-button @click="cancels">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 打开图片 -->
    <el-dialog :visible.sync="dialogVisible" size="tiny">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import {
  listActivities,
  addActivities,
  deleteActivities
} from "@/api/reviewActivities/management";
export default {
  name: "management.vue",
  data() {
      const validateStartTime = (rule, value, callback) => {
      if (!value){
       callback(new Error('请填写开始时间'))
      }else{
        let formFather = this.formFather;
        if (formFather.effectiveEndTime && new Date(value).getTime() > new Date(formFather.effectiveEndTime).getTime()) {
          callback(new Error('开始时间不能大于结束时间'));
        } else {
          callback()
        }
      }
    };
    const validateEndTime = (rule, value, callback) => {
      if (!value){
       callback(new Error('请填写结束时间'))
      }else{
        let formFather = this.formFather;
        if (formFather.effectiveStartTime && new Date(value).getTime() < new Date(formFather.effectiveStartTime).getTime()) {
          callback(new Error('结束时间不能小于开始时间'));
        } else {
          callback()
        }
      }
    };
    return {
      //查询参数
      queryParams: {
        page: 1,
        pageSize: 10,
        name: "",
        app: "",
        city: ""
      },
       // 总条数
      total: 0,
      fileList: [],
      checkboxArr: ["认证经纪人", "非认证经纪人"],
      codeOptions: { mode: "code" },
      jumpList: [], //跳转类型
      // 遮罩层
      loading: true,
      // 是否显示弹出层
      open: false,
      openFather: false,
      openDetail: false,
      title: "", //标题
      dialogImageUrl: "",
      dialogVisible: false,
      // 数据字典
      locationDic: [],
      getActivitiesDetails: [],
      activitiesTypeOptions: [],
      userTypeOptions: [],
      citysOptions: [],
      formFather: {
        id: "", //id
        app: "", //应用名称
        comCode: "", //认证经纪人
        name: "", //推荐位名称
        description: "", //推荐位描述
        link: "", //跳转link
        imageUrl: "", //图片ID
        effectiveStartTime: "", //开始时间
        effectiveEndTime: "", //结束时间
        jumpType: "", //跳转类型
        param: "", //附加参数
        order: "", //排序字段
        city: "" //城市  使用code
      },
      // 验证
      rules: {
        city: [{ required: true, message: "请选择城市", trigger: "change" }],
        order: [{ required: true, message: "请选择排列顺序", trigger: "change" }],
        app: [{ required: true, message: "活动名称不能为空", trigger: "change" }],
        name: [{ required: true, message: "请选择推荐位类型", trigger: "change" }],
        effectiveStartTime: [{ required: true, validator: validateStartTime ,trigger: "change" }],
        effectiveEndTime: [{ required: true, validator: validateEndTime ,trigger: "change" }],
        comCodeList: [{type: "array",required: true,message: "至少选择一个适用范围",trigger: "change"}],
        imageUrl: [{ required: true, message: "请上传图片", trigger: "change" }]
      }
    };
  },
  created() {
    // 获取数据字典
    this.getLocationDic();
    // 获取活动列表
    this.getList();
  },
  methods: {
    onError(e) {
      console.log("11", e);
    },
    onJsonChange(value) {
      console.log("value:", value);
    },
    //移除图片
    handleRemove(file, fileList) {
      this.$message({
        type: "info",
        message: "已删除原有图片",
        duration: 1000
      });
      this.formFather.imageUrl = "";
    },

    // 获取数据字典
    getLocationDic() {
      this.getDicts("location").then(response => {
        this.locationDic = response.data;
      });
      this.getDicts("jump_type").then(response => {
        this.jumpList = response.data;
      });
      this.getDicts("user_type").then(response => {
        this.userTypeOptions = response.data;
      });
      this.getDicts("location_type").then(response => {
        this.activitiesTypeOptions = response.data;
      });
      this.getDicts("sys_user_city").then(response => {
        this.citysOptions = response.data;
      });
    },
    // 图片上传成功处理
    handleSuccess(res, file) {
      if (file.response.length > 0) {
        this.$message({
          type: "info",
          message: "图片上传成功",
          duration: 3000
        });
        this.$refs.formFather.clearValidate('imageUrl');
        this.formFather.imageUrl = "https://api.shulanfd.com/aist-filesvr-web/api/files/" + file.response[0].id;

        // 解决验证通不过问题
        let tempFrom = JSON.parse(JSON.stringify(this.formFather));
        this.formFather = tempFrom;
      } else {
        this.$message({
          type: "error",
          message: "图片上传失败",
          duration: 3000
        });
      }
    },

    //排序
    changeTableSort(column) {
      //获取字段名称和排序类型
      var fieldName = column.prop;
      var sortingType = column.order;
      if (fieldName == "createTime") {
        if (sortingType == "descending") {
          this.queryParams.sortType = "descending";
        } else {
          this.queryParams.sortType = null;
        }
        this.getList();
      }
    },
    statusFormat(row, column) {
      return this.selectDictLabel(this.activitiesTypeOptions, row.locationType);
    },
    userFormat(row, column) {
      return this.selectDictLabel(this.userTypeOptions, row.userType);
    },
    getList() {
      this.loading = true;
      let data = this.queryParams;
      listActivities(data).then(response => {
        this.getActivitiesDetails = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    //搜索按钮
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    //重置按钮
    resetQuery() {
      this.queryParams.page = 1;
      this.resetForm("queryForm");
      this.getList();
    },
    // 表单重置
    reset() {
      this.queryParams.page = 1;
      this.getList();
      this.resetForm("formFather");
    },

    //添加按钮
    handleAdd(row) {
      this.initializa()
      this.openFather = true;
      this.title = "新增内容";
      this.resetForm("formFather");
      this.fileList = [];
      this.formFather = { comCodeList: ['认证经纪人'],effectiveStartTime:'',effectiveEndTime:'',param :{}};
    },
    //删除按钮
    handleDelete(row) {
      this.$confirm("是否确认删除数据?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return deleteActivities(row.id);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function() {});
    },
    //修改按钮
    handleUpdate(row) {
      this.initializa()
      this.formFather = { comCodeList: ['认证经纪人'],effectiveStartTime:'',effectiveEndTime:'',param :{}};
      this.fileList = []
      this.openFather = true;
      this.title = "修改内容";
      this.formFather = { ...row };
      this.formFather.param =  JSON.parse(row.param);
      this.fileList[0] = { url: row.imageUrl };

    },
    // 初始化弹框数据
    initializa(){
      this.formFather.id = ''
      this.formFather.app = ''
      this.formFather.comCode = ''
      this.formFather.name = ''
      this.formFather.description = ''
      this.formFather.link = ''
      this.formFather.imageUrl = ''
      this.formFather.effectiveStartTime = ''
      this.formFather.effectiveEndTime = ''
      this.formFather.jumpType = ''
      this.formFather.param = ''
      this.formFather.order = ''
      this.formFather.city = ''   
    },
    //确定按钮
    submitFormFather() {
      
      let id = this.formFather.id
      let app = this.formFather.app
      let comCode = this.formFather.comCode
      let name = this.formFather.name
      let description = this.formFather.description
      let link = this.formFather.link
      let imageUrl = this.formFather.imageUrl
      let effectiveStartTime = this.formFather.effectiveStartTime
      let effectiveEndTime = this.formFather.effectiveEndTime
      let jumpType = this.formFather.jumpType
      let param = JSON.stringify(this.formFather.param)
      let order = this.formFather.order
      let city = this.formFather.city
      let comCodeList = this.formFather.comCodeList
      let data ={
        id:id,
        app:app,
        comCode:comCode,
        name:name,
        description:description,
        link:link,
        imageUrl:imageUrl,
        effectiveStartTime:effectiveStartTime,
        effectiveEndTime:effectiveEndTime,
        jumpType:jumpType,
        param:param,
        order:order,
        city:city,
        comCodeList:comCodeList
      };
      this.$refs["formFather"].validate(valid => {
        if (valid) {
          if (this.formFather.id) {
            addActivities(JSON.stringify(data)).then(response => {
              if (response.data == 1) {
                this.$message("修改成功");
                this.cancels();
                this.reset();
              } else if (response.data == -1) {
                this.$message("推荐位类型或者应用名称不能重复添加");
              }
            });
          } else {
            addActivities(JSON.stringify(data)).then(response => {
              if (response.data == 1) {
                this.$message("添加成功");
                this.cancels();
                this.reset();
              } else if (response.data == -1) {
                this.$message("推荐位类型或者应用名称不能重复添加");
              }
            });
          }
        }
      });
    },
    //上传的文件个数超出设定时触发的函数
    onExceed(files, fileList) {
      this.$message({
        type: "info",
        message: "最多只能上传一个图片",
        duration: 5000
      });
    },
    beforeAvatarUpload(file) {
      // 文件类型进行判断
      const isJPG = /^image\/(jpeg|png|jpg)$/.test(file.type);
      if (!isJPG) {
        this.$message.error("上传图片只能是 image/jpeg/png 格式!");
      }
      return isJPG;
    },
    cancels() {
      this.openFather = false;
      this.openDetail = false;
    },
    //查看图片
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //关闭
    close() {
      this.openDetail = false;
    }
  }
};
</script>

<style scoped></style>
